<?php
/**
 * upload文件浏览器
 *
 * @version      0.0.0
 * @author      by huwhois
 * @time        2017/11/27
 */
namespace app\admin\controller;

use think\Request;

class FileManager extends Base
{
    
    public function index($activepath = '')
    {
        return $this->explorer();
    }

    public function explorer($activepath = '')
    {
        if ($activepath=='') {
            $activepath='uploads';
        }

        $inpath = "";

        $inpath = ROOT_PATH . 'public' . DS . $activepath;

        $dirhandle = scandir($inpath);

        $dirs = $files = array();

        define('BKM', 1024);

        foreach ($dirhandle as $val) {
            if ($val == "." || $val == "..") {
                continue;
            } elseif (is_dir($inpath.DS.$val)) {
                $dirs[] = $val;
            } else {
                $arr = array();

                $file = '';

                $arr['name'] = $val;

                $file = "$inpath/$val";

                $arr['extension'] = pathinfo($file, PATHINFO_EXTENSION);

                $filesize = floatval(filesize($file));

                if ($filesize>BKM) {
                    $filesize =  round($filesize/BKM, 2);

                    if ($filesize>BKM) {
                        $filesize = round($filesize/BKM, 2);
                    
                        $filesize .="M";
                    } else {
                        $filesize .="K";
                    }
                } else {
                    $filesize .="B";
                }

                $arr['size'] = $filesize;

                $filetime = filemtime("$file");

                $arr['time'] = date("Y-m-d H:i:s", $filetime);

                $files[] = $arr;
            }
        }
        // var_dump($files);
        // // var_dump($dirs);
        // exit;
        $counts = count($dirs)+count($files);

        $this->assign('counts', $counts);

        $this->assign('dirs', $dirs);

        $this->assign('files', $files);

        $activeurl = preg_replace("#[\/][^\/]*$#i", "", $activepath);

        $this->assign('activeurl', $activeurl);
        
        $this->assign('activepath', $activepath);

        return $this->fetch('explorer');
    }

    /**
     * 查看图片
     */
    public function preview($filename)
    {
        $this->assign('filename', $filename);
        return $this->fetch();
    }

    public function del($activepath = '', $filename = '')
    {
        $activepath = str_replace('/', DS, $activepath);
        if (Request::instance()->isAjax()) {
            if (unlink(ROOT_PATH.'public'.DS.$activepath.DS.$filename)) {
                return ['status'=>1,'msg'=>'success'];
            } else {
                return ['status'=>0,'msg'=>'failed'];
            }
        }
    }

    public function upload()
    {
        if (Request::instance()->isPOST()) {
            $isthumb = input('post.isthumb');
            $file = request()->file('image');
            // var_dump($files);
            // exit;
            $validate = ['size'=>2097152,'ext'=>'jpg,png,gif,jpeg'];

            $info = $file->validate($validate)->move(ROOT_PATH . 'public' . DS . 'uploads');
    
            if ($info) {
                if ($isthumb == 1) {
                    $filename = $info->getSaveName();

                    $thumbname = make_thumb($filename);

                    if (!$thumbname) {
                        $this->error('缩略图生成失败');
                    }
                }
                
                $this->success('上传成功', 'index');
            } else {
                $this->error($info->getExtension());
            }
        } else {
            return $this->fetch();
        }
    }

    /**
     * 站内选择缩略图
     *
     * @param string $activepath
     * @return void
     */
    public function addThumb($activepath = '')
    {
        if ($activepath=='') {
            $activepath='uploads';
        }

        $inpath = "";

        $inpath = ROOT_PATH . 'public' . DS . $activepath;

        $dirhandle = scandir($inpath);

        $dirs = $files = array();

        define('BKM', 1024);

        foreach ($dirhandle as $val) {
            if ($val == "." || $val == "..") {
                continue;
            } elseif (is_dir($inpath.DS.$val)) {
                $dirs[] = $val;
            } else {
                $arr = array();

                $file = '';

                $arr['name'] = $val;

                $file = "$inpath/$val";

                $arr['extension'] = pathinfo($file, PATHINFO_EXTENSION);

                $filesize = floatval(filesize($file));

                if ($filesize>BKM) {
                    $filesize =  round($filesize/BKM, 2);

                    if ($filesize>BKM) {
                        $filesize = round($filesize/BKM, 2);
                    
                        $filesize .="M";
                    } else {
                        $filesize .="K";
                    }
                } else {
                    $filesize .="B";
                }

                $arr['size'] = $filesize;

                $filetime = filemtime("$file");

                $arr['time'] = date("Y-m-d H:i:s", $filetime);

                $files[] = $arr;
            }
        }

        $counts = count($dirs)+count($files);

        $this->assign('counts', $counts);

        $this->assign('dirs', $dirs);

        $this->assign('files', $files);

        $activeurl = preg_replace("#[\/][^\/]*$#i", "", $activepath);

        $this->assign('activeurl', $activeurl);
        
        $this->assign('activepath', $activepath);

        return $this->fetch();
    }

    public function uploadThumb()
    {
        if (Request::instance()->isAjax()) {
            $file = request()->file('upload_file');

            $validate = ['size'=>2097152,'ext'=>'jpg,png,gif,jpeg'];

            $info = $file->validate($validate)->move(ROOT_PATH . 'public' . DS . 'uploads');
        
            if ($info) {
                $filename = $info->getSaveName();

                $thumbname = $this->makeThumb($filename);

                $thumbname = 'uploads/' . str_replace(DS, '/', $thumbname);

                if (!$thumbname) {
                    return ['status'=>0, 'imgname'=>'', 'msg'=>'缩略图生成失败'];
                }
            }

            $filename = 'uploads/' . str_replace(DS, '/', $filename);

            return ['status'=>1, 'bar'=>$filename, 'imgname'=>$thumbname, 'msg'=>'上传成功'];
        }
    }

    //判断(远程)文件是否为图片
    public function isImg($filename = '')
    {
        if (Request::instance()->isAjax()) {
            try {
                $mimetype = exif_imagetype($filename);
                // var_dump($mimetype);exit;
                if ($mimetype == IMAGETYPE_GIF || $mimetype == IMAGETYPE_JPEG || $mimetype == IMAGETYPE_PNG) {
                    return ['status'=>1,'msg'=>'图片地址可用'];
                //     $image = \think\Image::open($filename);
                //     $fileinfo= pathinfo($filename);
            //$thumbname = $fileinfo['dirname'].DS.'thumb'.DS.$fileinfo['filename'].'_thumb.'.$fileinfo['extension'];
                //     // echo $thumbname;exit;
                //     $test=$image->thumb($width,$height,\think\Image::THUMB_FIXED)->save($thumbname);
                } else {
                    return ['status'=>0, 'imgname'=>'', 'msg'=>'该图片不合法'];
                }
            } catch (\Exception $e) {
                return ['status'=>0, 'imgname'=>'', 'msg'=>'地址不合法'];
            }
        }
    }

    /**
     * 生成缩略图
     */
    public function makeThumb($filename)
    {
        $file = ROOT_PATH . 'public' . DS . 'uploads'. DS . $filename;
        
        $ext = pathinfo($file, PATHINFO_EXTENSION);

        $thumbname = str_replace('.' . $ext, '', $filename);

        $thumbname .='_thumb.' . $ext;

        $image = \think\Image::open($file);

        $result = $image->thumb(280, 160, 6)->save(ROOT_PATH . 'public' . DS . 'uploads'. DS . $thumbname);
        
        if ($result) {
            return $thumbname;
        } else {
            return false;
        }
    }
}
